<?php

/**
 *  角色管理
 */

namespace app\admin\service;

use app\admin\model\Menu as ModelMenu;
use app\facade\Basic;
use app\admin\model\Role as RoleModel;
use app\admin\model\RoleAuth;
use app\admin\common\ServiceResponse;
use think\facade\Db;
use think\Model;

class Role extends BaseService
{

    use ServiceResponse;

    protected $model;
    protected $menuIds = [];
    public function __construct()
    {
        Parent::__construct();
        $this->model = new RoleModel();
    }
    /**
     * @describe 获取部门列表
     * @author: Bobo
     * @date: 2024-06-05 18:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList(array $where, int $page, int $limit)
    {


        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }
        $total = $this->model->where($where)->count();
        $list = $this->model
            ->where($where)
            ->page($page, $limit)
            // ->append(['creator_value', 'updater_value'])
            ->select()->toArray();

        $data = ['list' => $list, 'total' => $total];
        return $this->success($data);
    }


    /**
     *  创建角色
    */
    public function create($param)
    {
        $role = [];
        $role['name'] = $param['name'];
        $role['remark'] = $param['remark'];
        $role['status'] = $param['status'];
        $role['create_time'] = date("Y-m-d H:i:s");
        $role['creator'] = $param['operator_id'];
        $role['order_range'] = $param['order_range'];
        $auth_ids = $param['auth_ids'];

        Db::startTrans();

        try {
            $RoleAuth = new RoleAuth();

            /* 设置 */
            $result = RoleModel::create($role);

            /* 批量写入 */
            $auth_data = [];
            if (is_array($auth_ids)) {
                foreach ($auth_ids as $value) {
                    $auth_data[] = [
                        'roleid' => $result->id,
                        'menuid' => $value,
                        'create_time' => date('Y-m-d H:i:s'),
                        'creator' => $param['operator_id']
                    ];
                }
                $RoleAuth->saveAll($auth_data);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            return Basic::data(1,'添加失败');
        }
        $this->logger->logOperation(null, 'Role', '创建', '创建角色');
        return Basic::data(0, '添加成功');


    }


    /**
     *  角色详情
     */
    public function detail($param)
    {

        $result = RoleModel::where('id', $param['id'])->field('id,name,status,remark,order_range')->find();

        if ( $result ) {
            $result = $result->toArray();
            $roleAuth = RoleAuth::where('roleid',$result['id'])->field('menuid')->select();
            if($roleAuth){
                foreach ($roleAuth as $value){
                    $this->menuIds[] = $value['menuid'];
                }
            }
        } else {
            $result['status'] = 1;
            $result['name'] = '';
            $result['remark'] = '';
        }

        $result['auth_ids'] = $this->menuIds;
        $result['menu'] = $this->MenuList();

        return Basic::data(0, 'ok', $result);
    }

    /**
     *  菜单列表
     */
    public function MenuList()
    {
        $result = ModelMenu::where('is_del',0)->select();
        if( $result ) {
            $result = $result->toArray();
        } else {
            $result = [];
        }
        return $this->menu_tree($result);
    }

    /**
     *  菜单递归处理
     */
    function menu_tree(array $data, $parent_id = 0) {

        $branch = [];
        foreach ($data as $value) {
            $element = [];
            $element['id'] = $value['id'];
            $element['type'] = $value['type'];
            $element['parent_id'] = $value['parent_id'];
            $element['title'] = $value['name'];
            if ($value['parent_id'] == $parent_id) {
                $children = $this->menu_tree($data, $value['id']);

                if ($children) {
                    if($children[0]['type'] == 3) {
                        $element['role'] = $children;

                        $permission = [];
                        foreach ($children as $v) {
                            if ( in_array($v['id'],$this->menuIds) ) {
                                $permission[] = $v['id'];
                            }
                        }

                        $element['permission'] = $permission;
                    } else {
                        $element['children'] = $children;
                    }
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }

    /**
     *  添加编辑角色
     */
    public function save($param)
    {

        $insData = [];
        $insData['id'] = $param['id'];
        $insData['name'] = $param['name'];
        $insData['status'] = $param['status'];
        $insData['remark'] = $param['remark'];
        $insData['order_range'] = $param['order_range'];

        if (empty($insData['id'])) {

            /* 验证角色是否已存在 */
            if (RoleModel::where('name', '=', $param['name'])->find()) {
                return Basic::data(1, '角色已存在');
            }

            /* 添加角色 */
            unset($insData['id']);
            $insData['is_del'] = 0;
            $insData['create_time'] = date('Y-m-d H:i:s');
            $insData['creator'] = $param['operator_id'];

            $result = RoleModel::create($insData);
            if ($result) {
                $this->logger->logOperation($result->id, 'Role', '添加', '添加角色');
                return Basic::data(0, '保存成功');
            } else {
                return Basic::data(1, '保存失败');
            }

        } else {

            /* 修改权限 */
            $insData['updater'] = $param['operator_id'];
            $insData['update_time'] = date('Y-m-d H:i:s');
            $result = RoleModel::update($insData);
            if ($result) {
                $this->logger->logOperation($result->id, 'Role', '添加', '添加角色');
                return Basic::data(0, '修改成功');
            } else {
                return Basic::data(1, '修改失败');
            }

        }
    }

    /**
     *  设置角色和角色关联
     */
    public function update($param)
    {

        $auth_ids = $param['auth_ids'];
        $role = [];
        $role['id'] = $param['role_id'];
        $role['name'] = $param['name'];
        $role['status'] = $param['status'];
        $role['remark'] = $param['remark'];
        $role['order_range'] = $param['order_range'];

        $menu_ids = ModelMenu::where('id','in',$auth_ids)->field('id')->where('type','in',[2,3])->select();
        if (!$menu_ids) {
            return Basic::data(1, '菜单不存在');
        }

        $auth_ids = array_unique(array_column($menu_ids->toArray(), 'id'));


        if (is_array($auth_ids)) {
            $insData = [];
            foreach ($auth_ids as $key => $value) {
                $insData[] = [
                    'roleid' => $role['id'],
                    'menuid' => $value,
                    'create_time' => date('Y-m-d H:i:s'),
                    'creator' => $param['operator_id']
                ];
            }
            Db::startTrans();
            try {
                $RoleAuth = new RoleAuth();

                /* 设置 */
                RoleModel::update($role);

                /* 清空设置 */
                $RoleAuth->where('roleid',$role['id'])->delete();

                /* 批量写入 */
                $RoleAuth->saveAll($insData);
                $this->logger->logOperation(null, 'Role', '修改', '设置角色和角色关联');
                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
                return Basic::data(1,'设置失败');
            }

            return Basic::data(0, '设置成功');

        } else {
            return Basic::data(1, 'auth_ids 格式错误');
        }
    }

    /**
     *  更新状态
    */
    public function status($param){


        $result = RoleModel::where('id','in',$param['ids'])->select();

        if (!$result) {
            return Basic::data(1, '角色不存在');
        }

        $result = RoleModel::where('id','in',$param['ids'])->update([
            'updater' => $param['operator_id'],
            'status' => $param['status'],
            'update_time' => date("Y-m-d H:i:s")
        ]);


        if ( $result ) {
            $this->logger->logOperation($param['ids'], 'Role', '更新', '更新状态');
            return Basic::data(0,'设置成功');
        } else {
            return Basic::data(1,'更新失败');
        }


    }


    /**
     *  删除角色 ( 软删除)
     */
    public function delete($param)
    {

        $result = RoleModel::where('id', $param['id'])->find();


        if (!$result) {
            return Basic::data(1, '角色不存在');
        }

        if ($result->is_del != 0) {
            return Basic::data(1, '已经被删除');
        }

        Db::startTrans();

        try {

            $result->is_del = time();
            $result->update_time = date("Y-m-d H:i:s");
            $result->save();

            RoleAuth::where('roleid',$result->id)->delete();
            $this->logger->logOperation($result->id, 'Role', '删除', '删除角色');
            Db::commit();

        } catch (\Exception $e) {

            Db::rollback();
            return Basic::data(1,'删除失败');

        }

        return Basic::data(0,'删除成功');
    }

    public function getFieldEnum($param)
    {
        $result = $this->model->getFieldEnum($param['field']);
        return Basic::data(0, 'ok', $result);
    }

}
